
(function(window, document) {
  window.onload = function() {
    function getViewport() {
      let pageWidth = window.innerWidth;
      let pageHeight = window.innerHeight;
      if (typeof pageWidth !== 'number') {
        if (document.compatMode === 'CSS1Compat') {
          pageWidth = document.documentElement.clientWidth;
          pageHeight = document.documentElement.clientHeight;
        } else {
          pageWidth = document.body.clientWidth;
          pageHeight = document.body.clientHeight;
        }
      }
      return {
        width: pageWidth,
        height: pageHeight,
      }
    }
    /**
     * loadStatus
     * -1 未加载
     * 0 正在加载中
     * 1 加载成功
     * 2 加载失败
     */

    let errorCount = 1;
    let errorUrl = 'http://i1.ciimg.com/602367/d53d7cb9ae033eeb.jpg';
    function lazyload() {
      const allImage = [...document.querySelectorAll('.box img')];
      const height = getViewport().height;
      allImage.forEach((image) => {
        // 出现在视口内的立马开始加载
        if (image._loadStatus === undefined) {
          image._loadStatus = -1;
          image._errorCount = 0;
        }
        if (image._loadStatus !== -1 ) return;
        const imageRect = image.getBoundingClientRect();
        const viewportDis = imageRect.top > 0 ? height - imageRect.top : imageRect.bottom;
        if (viewportDis > 100) { // 在图片在视口中露出超过100px的距离时开始加载图片
          const src = image.getAttribute('data-src');
          image.onload = function() {
            this._loadStatus = 1;
            this.setAttribute('status', 'loaded');
            this.onload = null;
            this.onerror = null;
          };
          image.onerror = function() {
            this._loadStatus = 2;
            if (this.src === errorUrl) return;
            if (typeof this._errorCount === 'number') {
              this._errorCount += 1;
            }
            if (this._errorCount < errorCount) {
              this.src = this.src;
            } else {
              this.src = errorUrl;
              this.setAttribute('status', 'error');
              this.onload = null;
              this.onerror = null;
            }
          };
          image._loadStatus = 0;
          image.src = src;
        }
      });
    }
    lazyload();
    window.addEventListener('scroll', lazyload, false);

    document.getElementById('add').onclick = function() {
      const box = document.createElement('div');
      box.className = 'box';
      box.innerHTML = `<img class="fadeIn" data-src="http://i1.ciimg.com/602367/3b6b78815d620e71.png" src="http://i4.eiimg.com/602367/32f51206f29d842a.jpg" title="2" alt="2"/>`;
      document.querySelector('.container').appendChild(box);
      lazyload();
    };
  };
})(window, document);